package com.jiayou.autoconfig


import com.jiayou.WebSocketEndpoint
import com.jiayou.autoconfig.WebSocketAutoConfig.Companion.endpointMap
import com.jiayou.enmu.SocketBusiness
import com.jiayou.enmu.SocketWork
import com.jiayou.handler.MessageHandlerImpl
import org.apache.catalina.loader.WebappClassLoader
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.getBeanNamesForAnnotation
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.ApplicationListener
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.event.ContextRefreshedEvent
import java.io.File
import java.io.IOException
import java.net.URISyntaxException
import java.net.URL
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap


@Configuration
@EnableConfigurationProperties(WebSocketProperties::class)
@ConditionalOnWebApplication
class WebSocketAutoConfig {

    @Bean
    fun messageHandlerImpl() = MessageHandlerImpl<Any>()

    companion object {
        //                               父端点名         包名+类名             子端点名   方法名
        val endpointMap = HashMap<String, HashMap<Class<*>, List<HashMap<String, String>>>>()
    }

    //扫描业务类
    fun scan(_class: Class<*>) {
        try {
            val annotation = _class.getAnnotation(SocketBusiness::class.java)
            if (annotation != null) {
                val p = HashMap<Class<*>, List<HashMap<String, String>>>()//当前类的信息
                val childEndpoint = ArrayList<HashMap<String, String>>()//子节点列表
                _class.methods.forEach {
                    it.isAccessible = true
                    val socketWork = it.getAnnotation(SocketWork::class.java)
                    if (socketWork != null) {
                        childEndpoint.add(hashMapOf(socketWork.value to it.name))
                    }
                }
                p[_class] = childEndpoint
                endpointMap[annotation.value] = p
            }
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        }
    }

}